package com.ffs.game.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * @author ffs80
 * @date 2022/4/4 19:36
 */
public class HttpServer {

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workersGroup;
    private ServerBootstrap bootstrap;

    /**
     * 启动服务
     *
     * @param packageName api所在包名
     */
    public void startServer(String packageName) {

    }

    private void initServer() {
        this.bossGroup = new NioEventLoopGroup(4);
        this.workersGroup = new NioEventLoopGroup(8);
        this.bootstrap = new ServerBootstrap();
        this.bootstrap.group(bossGroup, workersGroup);
        this.bootstrap.channel(NioServerSocketChannel.class);
        //队列大小
        this.bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        //禁用Nagle算法
        this.bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        //接收缓冲区大小
        this.bootstrap.childOption(ChannelOption.SO_RCVBUF, 1024 * 10);
        //发送缓冲区大小
        this.bootstrap.childOption(ChannelOption.SO_SNDBUF, 1024 * 10);
        this.bootstrap.childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast(new HttpServerCodec());
                pipeline.addLast(new HttpObjectAggregator(1024 * 10));
                pipeline.addLast(new ResponseEncode());
                pipeline.addLast(new ResponseEncode());
                pipeline.addLast(new HttpHandler());
            }
        });
    }
}
